package com.zhny.aiot.head.observe.control.plugin;

import com.google.common.collect.ImmutableMap;
import com.zhny.aiot.head.observe.control.plugin.model.HeadControlStoreEntry;
import com.zhny.aiot.plugin.ICenterFacilities;
import com.zhny.aiot.plugin.IDeviceFactory;
import com.zhny.aiot.plugin.core.utils.MessageUtils;
import com.zhny.aiot.plugin.model.DeviceEntity;
import com.zhny.aiot.plugin.model.MessageEntry;
import com.zhny.aiot.plugin.model.MessageType;
import com.zhny.aiot.plugin.model.TaskEntity;
import com.zhny.aiot.plugin.zhnygateway.GatewayEngine;
import com.zhny.aiot.plugin.zhnygateway.device.ZhnyConfig;
import com.zhny.aiot.plugin.zhnygateway.device.ZhnyDevice;
import com.zhny.aiot.plugin.zhnygateway.model.GatewayResponseMessage;
import com.zhny.aiot.plugin.zhnygateway.model.NodeRequestMessage;
import org.pf4j.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

public class HeadControlDevice extends ZhnyDevice<HeadControlStoreEntry> {
    private static final Logger logger = LoggerFactory.getLogger(HeadControlDevice.class);
    private final Map<String, Integer> CommandOperations;
    public HeadControlDevice(GatewayEngine engine, IDeviceFactory<ZhnyConfig> factory, ICenterFacilities centerFacilities, DeviceEntity entity) {
        super(engine, factory, centerFacilities, entity);
        CommandOperations =  new ImmutableMap.Builder<String, Integer>()
                .put("openA", 0x01)
                .put("closeA", 0x02)
                .put("openB", 0x03)
                .put("closeB", 0x04)
                .put("queryStatus", 0x0d).build();
    }

    @Override
    public void onDecoder(GatewayResponseMessage message) {
        logger.info (message.toString ());
        int type = message.getDeviceType ();
        if(type == 04){
            logger.info("---start decoder head control message---");
            onMessage(message);
        }
        if(message.getDeviceData() !=null)
            message.getDeviceData ().release ();
    }

    private void onMessage(GatewayResponseMessage message) {
        MessageEntry resultMsg = MessageUtils.createMessageEntry (this.getId ());
        resultMsg.setType(MessageType.RESULT);
        HeadControlStoreEntry storeEntry = new HeadControlStoreEntry ();
        int operation = message.getDeviceOper ();
        if(operation >= 0x01 && operation <= 0x04){
            if(message.getDataLength () < 5){
                resultMsg.setType (MessageType.ERROR);
                resultMsg.setData ("水利机械阀加入任务失败");
                logger.error ("[deviceNo:{},controllerNo:{}] 水利机械阀加入任务[{}]失败"
                        , getConfig ().getAddress (), getConfig ().getChannelNo (), operation);
                nofity (resultMsg);
                return;
            } else if(operation == 0x01){
                storeEntry.setWaterPumpA (true);
                resultMsg.setData (storeEntry);
            } else if(operation == 0x02){
                storeEntry.setWaterPumpA (false);
                resultMsg.setData (storeEntry);
            } else if(operation == 0x03){
                storeEntry.setWaterPumpB (true);
                resultMsg.setData (storeEntry);
            }else if(operation == 0x04){
                storeEntry.setWaterPumpB (false);
                resultMsg.setData (storeEntry);
            }
        } else if(operation == 0x0d) {
            Boolean valve1Status = message.getDeviceData ().readUnsignedByte ()==1?true:false;
            storeEntry.setWaterPumpA (valve1Status);
            Boolean valve2Status = message.getDeviceData ().readUnsignedByte ()==1?true:false;
            storeEntry.setWaterPumpB (valve2Status);
            message.getDeviceData().skipBytes(4);
            resultMsg.setData (storeEntry);
        }
        logger.info("head control store[{}]",storeEntry.toString());
        saveReal (storeEntry);
        nofity (resultMsg);
    }

    @Override
    protected NodeRequestMessage onCommand(TaskEntity taskEntity) {
        if(StringUtils.isNullOrEmpty (taskEntity.getMethodName ()))
            return null;

        Map<String,Object> command = new HashMap<String, Object>();
        command.put (taskEntity.getMethodName (),null);
        logger.info ("config address[{}]",Integer.parseInt (getConfig ().getAddress ()));
        return encode (command);
    }

    private NodeRequestMessage encode(Map<String, Object> commandMap) {
        for (String id : commandMap.keySet ()){
            if(CommandOperations.containsKey(id)) {
                Integer oper=CommandOperations.get(id);
                int length=4;
                return new NodeRequestMessage(getzhnyType() + 128, length, oper, Integer.parseInt(getConfig().getAddress()), null);
            }
        }
        return null;
    }

    @Override
    protected int getzhnyType() {
        return 4;
    }

    @Override
    protected void disposable() {

    }
}
